import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getUserInfo, removeUserInfo } from '@/utils/auth'

//axios.defaults.baseURL = 'http://192.168.0.51:8091'; //  配置接口地址 李彬
//const dataServiceUrl = "http://192.168.0.51:8086";
//const userServiceUrl = "http://192.168.0.51:8091";
//md5 base64加密处理 qs做json处理
const Base64 = require("js-base64").Base64,
    $md5 = require('js-md5'),
    qs = require('qs');

let service = (url, params, systemType, isBlob) => {

  //根据系统类别，对url拼入系统请求根路径
  if(systemType=="personService"){//人脸系统
    axios.defaults.baseURL = process.env.BASE_API+'hr/' // api 的 base_url
  } else if(systemType=="permissionService"){//人脸系统
    axios.defaults.baseURL = process.env.BASE_API+'permission/' // api 的 base_url
  } else{//默认使用用户权限系统
    axios.defaults.baseURL = process.env.BASE_API // api 的 base_url
  }
  //登录后randomKey
  let entity_random = store.getters.roles ? store.getters.roles.randomKey : '';
  //base64编码
  let params_base =  Base64.encode(JSON.stringify(params));
  //md5加密
  let sign = $md5(params_base + entity_random);
  //设置请求超时时间
  let time = 10000;
  if (url==="/sysUpload/importUsers"){
    time = 60000;
  }
  if (url==="/exportData/exportUserCertificatePic"){
    time = 30000;
  }
  // 创建axios实例
  return axios({
    // baseURL: process.env.BASE_API, // api 的 base_url
    header:{'Content-Type':isBlob?'application/octet-stream;charset=utf-8':'application/json; charset=UTF-8'},
    url: url,
    method: 'post',
    data: params,
    timeout: time, // 请求超时时间
    responseType: isBlob ? 'blob':'json' //返回文件流
  });
};

// request拦截器
axios.interceptors.request.use(

    config => {
      //console.log(store.getters.roles);
      if(store.getters.roles){
        let entity_headers = {
          'Authorization': store.getters.roles ? 'Bearer '+store.getters.roles.authorization : 'Bearer ', // 让每个请求携带自定义token
          // 'Content-Type':'application/json; charset=UTF-8'
        };
        config.headers = entity_headers;
      }
      // config.headers['Content-Type'] = 'application/json; charset=UTF-8'; // form形式提交参数
      return config
    },
    error => {
        // Do something with request error
        console.log(error); // for debug
        Promise.reject(error)
    }
);
// response 拦截器
axios.interceptors.response.use(
    response => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
      const res = response.data;
      if (res.code !== 200) {
        // 401:其他客户端登录了;Token 过期了;
        if (res.code === 401) {
          if (Object.keys(store.getters.roles).length === 0) //防止多次弹框
            return;
          removeUserInfo();
          MessageBox.confirm(
            res.message,
            '登录退出', {
              confirmButtonText: '重新登录',
              // cancelButtonText: '取消',
              showCancelButton:false,
              showClose:false,
              closeOnClickModal:false,
              type: 'warning'
            }
          ).then(() => {
            store.dispatch('FedLogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
        }else if(res.code === 500 && res.data != 'phone' && res.data != 'account' && res.data != 'password' && res.data != 'verifyCode'){
          Message({
            message: res.message,
            type: 'warning',
            duration: 5 * 1000
          });
        }
        return response.data
      } else {
        return response.data
      }
    },
    error => {
        console.log('err' + error); // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        });
        return Promise.reject(error)
    }
);
export default service
